using B.S.XZYData.Api.Wrter.Application.Command.ZSH;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.ZSH
{
	/// <summary>
	/// 导出不良品项为 Excel（无样式，仅表头+数据）
	/// </summary>
	public class ExportDefectiveHandler : IRequestHandler<ExportDefectiveQuery, byte[]>
	{
		private readonly IBaseRepository<Defective> _repo;
		private readonly IBaseRepository<AccountModel> _accountRepo;
		
		public ExportDefectiveHandler(IBaseRepository<Defective> repo, IBaseRepository<AccountModel> accountRepo)
		{
			_repo = repo;
			_accountRepo = accountRepo;
		}

		public async Task<byte[]> Handle(ExportDefectiveQuery request, CancellationToken cancellationToken)
		{
			// 基础查询：排除已删除的不良品项
			var query = _repo.GetAll().Where(x => !x.IsDeleted);
			
			// 应用筛选条件
			if (!string.IsNullOrWhiteSpace(request.DefectiveCode))
				query = query.Where(x => x.DefectiveCode.Contains(request.DefectiveCode));
			if (!string.IsNullOrWhiteSpace(request.DefectiveName))
				query = query.Where(x => x.DefectiveName.Contains(request.DefectiveName));

			var list = query.OrderByDescending(x => x.CreateTime).ToList();

			// 获取所有相关的用户ID（转换为long类型以匹配AccountModel.Id）
			var creatorIds = list.Select(x => (long)x.CreatorId).Distinct().ToList();
			var modifierIds = list.Where(x => x.ModifierId.HasValue).Select(x => (long)x.ModifierId.Value).Distinct().ToList();
			var allUserIds = creatorIds.Concat(modifierIds).Distinct().ToList();

			// 批量查询用户信息
			var users = _accountRepo.GetAll().Where(u => allUserIds.Contains(u.Id)).ToList();

			IWorkbook wb = new XSSFWorkbook();
			var sheet = wb.CreateSheet("不良品项");
			
			// 创建中文表头
			var header = sheet.CreateRow(0);
			header.CreateCell(0).SetCellValue("编号");
			header.CreateCell(1).SetCellValue("不良品项编号");
			header.CreateCell(2).SetCellValue("不良品项名称");
			header.CreateCell(3).SetCellValue("附件路径");
			header.CreateCell(4).SetCellValue("图片路径");
			header.CreateCell(5).SetCellValue("创建时间");
			header.CreateCell(6).SetCellValue("创建人");
			header.CreateCell(7).SetCellValue("修改时间");
			header.CreateCell(8).SetCellValue("修改人");

			// 填充数据行
			for (int i = 0; i < list.Count; i++)
			{
				var defective = list[i];
				var r = sheet.CreateRow(i + 1);
				
				// 查找创建人和修改人名称
				var creatorName = users.FirstOrDefault(u => u.Id == (long)defective.CreatorId)?.RealName ?? "";
				var modifierName = defective.ModifierId.HasValue ? 
					users.FirstOrDefault(u => u.Id == (long)defective.ModifierId.Value)?.RealName ?? "" : "";

				r.CreateCell(0).SetCellValue(defective.Id);
				r.CreateCell(1).SetCellValue(defective.DefectiveCode ?? "");
				r.CreateCell(2).SetCellValue(defective.DefectiveName ?? "");
				r.CreateCell(3).SetCellValue(defective.AttachmentPath ?? "");
				r.CreateCell(4).SetCellValue(defective.ImagePath ?? "");
				r.CreateCell(5).SetCellValue(defective.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
				r.CreateCell(6).SetCellValue(creatorName);
				r.CreateCell(7).SetCellValue(defective.ModifyTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "");
				r.CreateCell(8).SetCellValue(modifierName);
			}

			using var ms = new MemoryStream();
			wb.Write(ms);
			return ms.ToArray();
		}
	}
}


